<template>
	<view>
		<view class="search" :style="{paddingTop:capsuleTop+'px',height:capsuleHeight+'px'}">
			<view @click="returnHandle" class="return" v-if="type != 'noReturnWhite'">
				<i class="iconfont icon-fanhuitubiao" :style="{color:'#3FD3D1',fontWeight:'bold'}"></i>
			</view>
			<view class="searchBox" :style="{
				width: type != 'noReturnWhite' ? '90%' : '100%',
				border: type == 'skyBlueAll' ? '2px solid #3FD3D1' : '0px solid #ffffff'
				}">
				<van-icon name="search" color="#AEAEAE" class="serchIcon" />
				<input :focus="focuComState" type="text" class="searchInput" v-model="inputkeyword"
					@input="searchChangeHandel" placeholder="请输入搜索内容" @confirm="gotoDetail(inputkeyword)" />
			</view>
		</view>
		<!-- 搜索建议列表 -->
		<view class="sugg-list" v-if="searchResultsStatus" :style="{height:suggHeight+'px'}">
			<view class="sugg-item" v-for="(item, i) in searchResults" :key="i" @click="gotoDetail(item)">
				<van-icon name="search" size='16px' color='#666' />
				<view class="goods-name">{{item}}</view>
			</view>
			<view class="noSugg-item">
				{{suggestText}}
			</view>
		</view>
		<!-- 搜索历史 -->
		<view class="history-box" v-if="historyList.length && searchHistory">
			<!-- 标题区域 -->
			<view class="history-title">
				<text>搜索历史</text>
				<van-icon name="delete-o" size="17" color='#000' v-if="historyIconStatus" @click='historyIcon()' />
				<view class="history-compile" v-if="historyCompilesStatus">
					<text class="history-empty" @click.stop="cleanHistory">清空</text>
					|
					<text class="history-cancel" @click.stop="historyCancel">取消</text>
				</view>
			</view>
			<!-- 列表区域 -->
			<view class="history-list">
				<view class="box" @longpress.stop='deleteiocn(item)' v-for="(item, i) in historys" :key="i"
					@click.stop="historyListSearch(item)">
					<user-select>{{item}}</user-select>
					<van-icon name="clear" size="16" class='delete-icon' v-if="deleteIconStatus" />
				</view>
				<view class="more-box" v-if="moreStatus" @click="hideHistory">
					<van-icon name="arrow-down" color='#666666' size="16" />
				</view>
			</view>
		</view>
		<!-- 搜索tabs -->
		<view class="search-details-left" v-if="isAllshow">
			<nav-list :navList="navList" @clickIndex="getClickIndexHandle" :active="active"></nav-list>
		</view>
		<!-- 吐槽 -->
		<scroll-view scroll-y enhanced v-if="isAllshow" :show-scrollbar="false" class="content"
			:style="{height:contentHeight + 'px'}" v-show="active === 0" @scrolltolower="lowerBottom('commentSearch')">
			<view v-for="item in communityInitialArray" :key='item.intactArticleId' class="communitybox">
				<public-comment :commentObject="item" @clickId='disposeId'></public-comment>
			</view>
			<view
				v-if="discloseQueryObj.totalPageNumber >= 1 && discloseQueryObj.pagenum == discloseQueryObj.totalPageNumber && !requestState"
				class="noData">
				已全部加载
			</view>
			<view v-if='disclosesStatus' class="bottomShow">没有找到你要搜索的内容...</view>
			<view class="recommend-community" v-if="disclosesListStatus">
				<view class="recommend-community-item" v-for="(item,index) in hotDiscloseArray" :key='item.articleId' @click='()=>gotoCommunityDetails(item)'>
						<view class="frame-item">{{index+1}}</view>
						<h1 class="text-item">{{item.title}}</h1>
				</view>
			</view>
		</scroll-view>
		<!-- 用户 -->
		<scroll-view scroll-y enhanced v-if="isAllshow" :show-scrollbar="false" class="content-background"
			:style="{height:contentHeight + 'px'}" v-show="active === 1" @scrolltolower="lowerBottom('userSearch')">
			<view class="boxx">
				<view v-for="item in userList" :key='item.userId' class="item" :style="{'border-radius':isRadius()}">
					<user-item :userObj="item" @changeUserFansState="changeUserFansStateHandle()" :all="0"
						@clickId='disposeId' :type='3'></user-item>
				</view>
			</view>
			
			<view
				v-if="userQueryObj.totalPageNumber >= 1 && userQueryObj.pagenum == userQueryObj.totalPageNumber && !requestState"
				class="noData">
				已全部加载
			</view>
			<view v-if="UserStatus" class="bottomShow">没有找到你要查找的用户...</view>
			<!-- 热门用户 -->
			<view class='recommend-community-box recommend-community-box-white' v-if="disclosesUserStatus">
				<view v-for="item in hotUserArray" :key='item.userId' class="item">
					<user-item :userObj="item" @changeUserFansState="changeUserFansStateHandles()" :all="0" @clickId='disposeId' :type='2'></user-item>
				</view>
			</view>
		</scroll-view>
		<van-dialog id="van-dialog" />
	</view>
</template>
<script>
	import {
		capsuleTopHeight
	} from "../../mixins/mixins.js"
	import Dialog from '../../wxcomponents/vant/dist/dialog/dialog.js';
	export default {
		mixins: [capsuleTopHeight],
		data() {
			return {
				suggestText: '已全部加载',
				suggHeight: 0,
				inputkeyword: '', //搜素关键字
				focuComState: false, //自动获取焦点
				hotDiscloseArray: [],//热门吐槽
				hotUserArray:[],
				showShare: false,
				moreStatus: false,
				moreList: [], //更多数据
				isAllshow: true,
				active: 0,
				historyCompilesStatus: false, //搜索历史编辑状态
				historyIconStatus: true, //搜索历史icon状态
				historyList: [], // 搜索关键词的历史记录
				searchResults: [], // 搜索结果列表
				allLoad: false,
				// tabs标题文本
				navList: [{
						text: "吐槽",
						id: '01'
					},
					{
						text: "用户",
						id: '02'
					}
				],
				contentHeight: 0, //内容高度
				searchResultsStatus: false, //搜索建议状态
				primary: true, // 控制搜索历史tags的显示
				disclosesListStatus: true, // 热门推荐状态
				disclosesUserStatus: true, // 热门用户状态
				disclosesStatus: false, // 搜索吐槽为无状态
				UserStatus: false, // 搜索用户为无状态
				searchHistory: true, //搜索历史状态
				communityInitialArray: [], // 搜索吐槽数据
				// 吐槽分页数据
				discloseQueryObj: {
					pagenum: 1,
					totalPageNumber: 0,
					pagesize: 0,
					total: 0,
				},
				userList: [], // 搜索用户数据
				userQueryObj: {
					pagenum: 1,
					totalPageNumber: 0,
					pagesize: 0,
					total: 0,
				},
				requestState: false, // 请求状态
				deleteIconStatus: false, //删除icon图标状态
			};
		},
		mounted() {
			setTimeout(() => {
				this.focuComState = this.focuState
			}, 300)
		},
		created() {
			this.historyList = JSON.parse(uni.getStorageSync('kw') || '[]')
			this.getScreenHeight()
			this.getHotDisclose()
			this.opinionMoreList()
			this.getHotUserArray()
		},
		methods: {
			async getHotUserArray(){
				const {
					data: res
				} = await uni.$http.get(
					`/ym_server/user/activeUser`
				);
				this.hotUserArray = res.data.data.splice(0,5)
			},
			isRadius(){
				if(this.userList.length===1){
					return '20px !important'
				}
			},
			gotoCommunityDetails(item) {
				console.log(item);
				uni.navigateTo({
					url: `../../subpkg/community-details/community-details?id=${item.id}`,
				});
			},
			opinionMoreList() {
				if (this.historyList.length >= 4) {
					this.moreStatus = true
					this.moreList = this.historyList.slice(4, this.historyList.length)
					this.historyList.splice(4, this.historyList.length)
				} else {
					this.moreStatus = false
				}
			},
			hideHistory() {
				this.moreStatus = false
				this.historyList = [...this.historyList, ...this.moreList]
			},
			// 下拉触底
			lowerBottom(type) {
				if (type === 'commentSearch') {
					if (this.discloseQueryObj.pagenum < this.discloseQueryObj.totalPageNumber) {
						this.discloseQueryObj.pagenum++
						this.gotoDetail(this.inputkeyword)
					}
				} else if (type === 'commentSearch') {
					if (this.userQueryObj.pagenum < this.userQueryObj.totalPageNumber) {
						this.userQueryObj.pagenum++
						this.gotoDetail(this.inputkeyword)
					}
				}
			},
			// 热门推荐
			async getHotDisclose() {
				const {
					data: res
				} = await uni.$http.get(
					`/ym_server/IntactArticle/hottestRecommendation`
				);
				this.hotDiscloseArray = res.data.data
			},
			historyCancel() {
				this.historyIconStatus = !this.historyIconStatus
				this.historyCompilesStatus = !this.historyCompilesStatus
				this.deleteIconStatus = false
			},
			historyIcon() {
				let arr = JSON.parse(uni.getStorageSync('kw'))
				if (arr.length <= 0) return Dialog.alert({
					message: '暂无搜索历史',
				})
				this.deleteIconStatus = true
				this.historyIconStatus = !this.historyIconStatus
				this.historyCompilesStatus = !this.historyCompilesStatus
			},
			historyListSearch(name) {
				if (this.historyCompilesStatus) {
					this.deleteiocn()
				} else {
					this.inputkeyword = ''
					this.inputkeyword = name
					this.gotoDetail(this.inputkeyword)
				}
			},
			// 删除
			deleteiocn(name) {
				let arr = JSON.parse(uni.getStorageSync('kw'))
				Dialog.confirm({
					message: '是否清除当前历史记录'
				}).then(() => {
					const set = new Set(this.historyList)
					// // 2. 调用 Set 对象的 delete 方法，移除对应的元素
					set.delete(name)
					this.historyList = Array.from(set)
					arr.splice(arr.indexOf(name), 1)
					uni.setStorageSync('kw', JSON.stringify(arr))
					this.historyList = JSON.parse(uni.getStorageSync('kw'))
					this.inputkeyword = ''
					this.communityInitialArray = [];
					this.userList = [];
					this.disclosesStatus = false;
					this.UserStatus = false;
					this.disclosesListStatus = true
					this.disclosesUserStatus = true
					if (arr.length == 0) {
						this.historyIconStatus = true
						this.historyCompilesStatus = false
					}
				})
			},
			// 用户关注状态改变事件
			async changeUserFansStateHandle(id, fansState) {
				const item = this.userList.find(item => item.userId == id)
				item.fansState = !fansState
				if (item.mutualConcern) {
					item.mutualConcern = false
				} else {
					item.mutualConcern = true
				}
			},
			changeUserFansStateHandles(id, fansState){
				const item = this.hotUserArray.find(item => item.userId == id)
				item.fansState = !fansState
				if (item.mutualConcern) {
					item.mutualConcern = false
				} else {
					item.mutualConcern = true
				}
			},
			//获取屏幕高度方法
			getScreenHeight() {
				const wxWindowHeight = uni.getSystemInfoSync().windowHeight
				this.suggHeight = wxWindowHeight - 90
				this.contentHeight = wxWindowHeight - this.capsuleHeight - this.capsuleTop - 80
			},
			// 用户点赞操作
			disposeId(id) {
				const result = this.communityInitialArray.find(item => item.intactArticleId === id)
				if (result.likeStatus == true) {
					result.likeStatus = false
					if (result.likeStatus == false) {
						result.article.likeNum -= 1
					}
				} else {
					result.likeStatus = true
					if (result.likeStatus == true) {
						result.article.likeNum += 1
					}
				}
			},
			// 搜索建议
			async searchChangeHandel(event) {
				clearTimeout(this.time)
				this.time = setTimeout(() => {
					if (event.detail.value.trim() == "" && event.detail.value.length != 0) return Dialog
				.alert({
						message: '请输入搜索内容',
					})
				}, 300)
				this.active = 0
				this.inputkeyword = event.detail.value.trim()
				if (this.inputkeyword === '') {
					this.requestState = true
					this.contentHeight = 700
					this.communityInitialArray = [];
					this.userList = [];
					this.disclosesStatus = false;
					this.UserStatus = false;
					this.disclosesListStatus = true
					this.disclosesUserStatus = true
					this.isAllshow = true
					this.searchHistory = true
					this.searchResultsStatus = false
					this.historyCompilesStatus = false
					this.deleteIconStatus = false
					this.historyIconStatus = true
					this.opinionMoreList()
					return
				}
				const {
					data: res
				} = await uni.$http.get(
					`/ym_server/IntactArticle/contentPrompt?content=${this.inputkeyword}`
				);
				if (res.code === 200) {
					if (res.data.data.length == 0) {
						this.suggestText = '暂无搜索建议'
						this.isAllshow = false
						this.searchResultsStatus = true
						this.searchResults = res.data.data
						this.searchHistory = false
					} else {
						this.isAllshow = false
						this.searchResultsStatus = true
						this.searchResults = res.data.data
						this.searchHistory = false
						this.suggestText = '已经全部加载'
					}
				}


			},
			async gotoDetail(goods_name) {
				this.inputkeyword = goods_name
				this.isAllshow = true
				this.searchHistory = false
				this.searchResultsStatus = false
				if (this.inputkeyword === '') {
					this.communityInitialArray = [];
					this.userList = [];
					this.disclosesStatus = false;
					this.UserStatus = false;
					this.disclosesListStatus = true
					this.disclosesUserStatus = true
					this.isAllshow = true
					this.searchResultsStatus = false
					this.searchHistory = true
					this.historyCompilesStatus = false
					this.deleteIconStatus = false
					this.historyIconStatus = true
					this.contentHeight = 700
					this.requestState = true
					this.opinionMoreList()
					return
				}
				if (this.isAllshow) {
					this.inputkeyword === ''
					if (this.active === 0) {
						this.requestState = true
						this.disclosesUserStatus = false
						this.communityInitialArray = []
						const {
							data: res
						} = await uni.$http.get(
							`/ym_server/IntactArticle/allSearch?str=${this.inputkeyword}&page=${this.discloseQueryObj.pagenum}`
						);
						console.log('吐槽', res)
						if (res.data.list === null || res.code === -1 || res.data.list.records.length === 0) {
							this.disclosesStatus = true
							this.disclosesListStatus = true
							this.contentHeight = this.getScreenHeight()
						} else {
							this.requestState = false
							this.disclosesStatus = false
							this.disclosesListStatus = false
							this.discloseQueryObj.totalPageNumber = res.data.list.pages;
							this.discloseQueryObj.pagesize = res.data.list.size;
							this.discloseQueryObj.total = res.data.list.total;
							this.communityInitialArray = [...this.communityInitialArray, ...res.data.list.records]
							this.getScreenHeight()
						}
					} else if (this.active === 1) {
						this.userList = []
						this.disclosesListStatus = false
						this.requestState = true
						const {
							data: list
						} = await uni.$http.get(
							`/ym_server/user/search?content=${this.inputkeyword}&page=${this.userQueryObj.pagenum}`
						);
						console.log('用户', list);
						if (list.data.list.records === [] || list.data.list.records.length == 0) {
							this.UserStatus = true
							this.disclosesUserStatus = true
							this.contentHeight = this.getScreenHeight()
						} else {
							this.requestState = false
							this.UserStatus = false
							this.disclosesUserStatus = false
							this.userQueryObj.totalPageNumber = list.data.list.pages;
							this.userQueryObj.pagesize = list.data.list.size;
							this.userQueryObj.total = list.data.list.total;
							this.userList = [...this.userList, ...list.data.list.records]
							this.getScreenHeight()
						}

					}
				}
				this.saveSearchHistory(this.inputkeyword)
			},
			saveSearchHistory(name) {
				const set = new Set(this.historyList)
				// 2. 调用 Set 对象的 delete 方法，移除对应的元素
				set.delete(name)
				// 3. 调用 Set 对象的 add 方法，向 Set 中添加元素
				set.add(name)
				// 4. 将 Set 对象转化为 Array 数组
				this.historyList = Array.from(set)
				//调用 uni.setStorageSync(key, value) 将搜索历史记录持久化存储到本地
				uni.setStorageSync('kw', JSON.stringify(this.historyList))
			},
			cleanHistory() {
				Dialog.confirm({
					message: '是否清空历史记录'
				}).then(() => {
					// 清空 data 中保存的搜索历史
					this.historyList = []
					// 清空本地存储中记录的搜索历史
					uni.setStorageSync('kw', '[]')
					this.historyCompilesStatus = false
					this.historyIconStatus = true
				})
			},
			getClickIndexHandle(index) {
				this.active = index
				this.gotoDetail(this.inputkeyword)
			}
		},
		computed: {
			historys() {
				// 注意：由于数组是引用类型，所以不要直接基于原数组调用 reverse 方法，以免修改原数组中元素的顺序
				// 而是应该新建一个内存无关的数组，再进行 reverse 反转
				return [...this.historyList].reverse()
			}
		}
	}
</script>
<style lang="scss">
	
	// 搜索
	.search {
		width: 520upx;
		display: flex;
		margin-left: 40upx;

		.return {
			display: flex;
			justify-content: center;
			align-items: center;
			padding-right: 20upx;

			image {
				height: 32upx;
			}
		}

		.searchBox {
			box-sizing: border-box;
			border-radius: 999upx;
			display: flex;
			border: 4upx solid #3FD3D1;
			background: #ffffff;
			align-items: center;

			.serchIcon {
				margin-left: 18upx;
				margin-right: 10upx;
				font-size: 36upx;
			}

			.searchInput {
				width: 80%;
				color: #AEAEAE;
				height: 100%;
				font-size: 28upx;

			}
		}
	}

	.noData {
		width: 100%;
		text-align: center;
		padding: 40upx 0upx;
		color: #AEAEAE;
		font-size: 24upx;
		border-top: solid #EEF2F4 1px;
	}

	.communitybox {
		margin: auto;
	}

	.content {
		padding: 0upx 32upx;
		box-sizing: border-box;
	}

	.content-background {
		padding: 0upx 32upx;
		box-sizing: border-box;
		margin-top: 24upx;

			.item{
				background: #fff;
				width: 100%;
				padding: 24upx;
				box-sizing: border-box;
				border-bottom: 1px solid #D1D1D1;
			}
			.item:first-child{
				border-radius: 20px 20px 0px 0px !important;
			}
			.item:last-child{
				border-bottom: 0px;
				border-radius: 0px 0px 20px 20px !important;
			}
	}
	.more-box {
		background: #F5F5F5;
		width: 24px;
		height: 24px;
		border-radius: 24px;
		padding: 15rpx;
		margin-top: 5px;
		box-sizing: border-box;
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.recommend-community-box-white {
		background: white;
		border-radius: 20px;
	}

	.box {
		min-width: 75rpx;
		text-align: center;
		line-height: 10rpx;
		border-radius: 30rpx;
		margin-top: 5px;
		margin-right: 10px;
		font-size: 26rpx;
		background: #F5F5F5;
		color: #7A7A7A;
		line-height: 30rpx;
		padding: 15rpx;
		margin-top: 10rpx;
		position: relative;

		.delete-icon {
			position: absolute;
			top: -3px;
			right: -3px;
		}

		user-select {
			display: -webkit-box;
			text-overflow: ellipsis;
			overflow: hidden;
			-webkit-box-orient: vertical;
			-webkit-line-clamp: 1;
		}

		>van-icon {
			margin-left: 8rpx;
			align-items: center;
			display: inline-flex;
			justify-content: center
		}
	}

	// 搜索建议
	.sugg-list {
		padding: 0 5px;
		background: #fff;
		margin-top: 12upx;
		border-radius: 20upx;

		.sugg-item {
			font-size: 12px;
			padding: 13px 13px;
			display: flex;
			align-items: center;
			border-bottom: 1px solid #EEF2F4;

			.goods-name {
				margin-left: 28rpx;
				// 文字不允许换行（单行文本）
				white-space: nowrap;
				// 溢出部分隐藏
				overflow: hidden;
				// 文本溢出后，使用 ... 代替
				text-overflow: ellipsis;
				margin-right: 3px;
			}
		}

		.noSugg-item {
			width: 100%;
			text-align: center;
			padding: 40upx 0upx;
			color: #AEAEAE;
			font-size: 24upx;
			border-top: solid #EEF2F4 1px;
		}
	}

	// 搜素tabs
	.search-details-left {
		width: 30%;
		margin: 0upx 28upx;
	}

	// 暂无吐槽
	.bottomShow {
		text-align: center;
		font-size: 22upx;
		padding: 40upx 0upx 10upx 0upx;
		color: #AEAEAE;
	}

	.recommend-community .recommend-community-item:first-child .frame-item {
		background: #EB4C39 !important;
	}

	.recommend-community .recommend-community-item:nth-child(2) .frame-item {
		background: #EE8041 !important;
	}

	.recommend-community .recommend-community-item:nth-child(3) .frame-item {
		background: #F2A748 !important;
	}

	.recommend-community {
		margin-top: 24upx !important;
		border-radius: 20px;
		background: url('@/static/bluebakcground.png') no-repeat;
		background-size: 100% 100%;
		margin: auto;
		display: flex;
		flex-direction: column;
		padding: 40upx;
		box-sizing: border-box;
		.recommend-community-item:last-child{
			margin-bottom: 0px;
		}
		.recommend-community-item {
			display: flex;
			align-items: center;
			position: relative;
			margin-bottom: 48upx;
				.frame-item {
					width: 32rpx;
					height: 32rpx;
					background: #cccccc;
					color: #fff;
					border-radius: 10rpx;
					margin-right: 10rpx;
					display: flex;
					align-items: center;
					justify-content: center;
				}

				.text-item {
					height: 100%;
					font-family: Source Han Sans CN;
					font-size: 28upx;
					font-weight: 550;
					letter-spacing: 1px;
					color: #333333;
					white-space:nowrap;
					text-overflow: ellipsis;
					overflow: hidden;
					-webkit-box-orient: vertical;
					-webkit-line-clamp: 1;
				}
			}
	}

	// 搜索历史
	.history-box {
		margin: auto;
		width: 684upx;
		padding: 0 5px;

		.history-title {
			display: flex;
			justify-content: space-between;
			align-items: center;
			height: 40px;
			font-size: 13px;
			border-bottom: 1px solid #efefef;

			.history-compile {
				.history-empty {
					margin-right: 5rpx;
				}

				.history-cancel {
					margin-left: 5rpx;
				}
			}
		}

		.history-list {
			display: flex;
			flex-wrap: wrap;

			.van-tag {
				margin-top: 5px;
				margin-right: 5px;
			}
		}
	}
</style>
